<?php


namespace App\Exports;


use App\Models\PartCompany;
use App\Models\ProjectClassify;
use App\Services\BaseService;
use App\Services\CommonService;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithCustomStartCell;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithTitle;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

/**
 * Class BookTitleExport29
 * @package App\Exports
 * 29号案卷目录导出格式
 */
class BookTitleExport29 implements  FromCollection, WithTitle, WithColumnWidths, WithStyles,  WithCustomStartCell
{
    use Exportable;

    protected  $totalRow; //总行数
    protected  $partCompanyId; //参见单位
    protected  $partCompanyName; //参见单位名字
    protected  $projectClassifyId; //项目分类
    protected  $projectClassifyName; //项目分类名称
    protected  $bookTitleIds; //指定的案卷

    public function __construct($bookTitleIds)
    {
        $this->partCompanyId       = request()->input('part_company_id', 0);
        $this->partCompanyName     = PartCompany::query()->where('id', $this->partCompanyId)->value('title');
        $this->projectClassifyId   = request()->input('project_classify_id', 0);
        $this->projectClassifyName = ProjectClassify::query()->where('id', $this->projectClassifyId)->value('title');
        $this->bookTitleIds        = $bookTitleIds;
    }

    /**
     * 获取数据集合
     */
    public function collection()
    {
        $bookTitleInstance = (new BaseService())->getBookTitleInstance($this->partCompanyId, $this->projectClassifyId);
        $bookTitleIds = $this->bookTitleIds;
        $list = $bookTitleInstance
            ->when($bookTitleIds, function ($query) use ($bookTitleIds) {
                return $query->whereIn('id', $bookTitleIds);
            })
            ->where('part_company_id', $this->partCompanyId)
            ->where('project_classify_id', $this->projectClassifyId)
            ->select('id', 'serial_no', 'archives_no', 'title', 'word_material', 'blueprint', 'page_num', 'store_period', 'start_date', 'end_date')
            ->orderBy('serial_no')
            ->get();

        if ($list->isEmpty()) return collect([]);

        $list = $list->toArray();

        $r_list = [];
        foreach ($list as $key => $val) {
            $arr['number']         = $val['serial_no'];  //序号
            $arr['archives_no']    = $val['archives_no'];   //档案号
            $arr['title']          = htmlspecialchars_decode($val['title']); //标题
            $arr['word_material']  = $val['word_material']; //文字材料
            $arr['blueprint']      = $val['blueprint'];     //蓝图
            $arr['total_page']     = $val['page_num'];      //总页数
            $arr['store_period']   = $val['store_period'];  //保管期限
            $arr['start_end_date'] = format_date($val['start_date'], $val['end_date']); //起止日期
            $arr['part_company']   = $this->partCompanyName;
            $arr['data_count']     = CommonService::getBookCatalogInstance($this->partCompanyId, $this->projectClassifyId)->where('book_title_id', $val['id'])->count() ?: 0;
            $r_list[]              = $arr;
        }
        $this->totalRow = count($r_list) + 3;

        return collect($r_list);
    }

    /**
     * sheet名称
     * @return string
     */
    public function title(): string
    {
        return $this->projectClassifyName;
    }

    /**
     * 设置列宽
     * @return array
     */
    public function columnWidths(): array
    {
        return [
            'A' => 10, 'B' => 30, 'C' => 60, 'D' => 6, 'E'=>10, 'F'=>6, 'G'=>10, 'H'=>15, 'I'=>30, 'J'=>7
        ];
    }

    /**
     * 从哪个单元格开始渲染数据，数据集合如 $list
     * @return string
     */
    public function startCell(): string
    {
        return 'A4';
    }

    /**
     * 对文字放不下的单元格设置字体字体
     */


    /**
     * 样式设置
     * @param Worksheet $sheet
     * @throws PhpSpreadsheetException
     */
    public function styles(Worksheet $sheet)
    {
        $sheet->getDefaultRowDimension()->setRowHeight(42); //设置行高(全部行高)
        $sheet->getStyle('A1:J'.$this->totalRow)->getFont()->setName('宋体'); //宋体
        $sheet->getStyle('C4:J'.$this->totalRow)->getFont()->setSize(10); //大小

        $sheet->mergeCells('A1:J1');
        $sheet->setCellValue('A1', '案卷目录');

        $sheet->mergeCells('A2:A3'); //序号
        $sheet->mergeCells('B2:B3'); //档案号
        $sheet->mergeCells('C2:C3'); //案卷题名
        $sheet->mergeCells('D2:F2'); //案卷页数
        $sheet->mergeCells('G2:G3'); //保管期限
        $sheet->mergeCells('H2:H3'); //起止日期
        $sheet->mergeCells('I2:I3'); //形成单位
        $sheet->mergeCells('J2:J3'); //卷内数量
        /**
         * 属性名设置
         */
        $sheet->setCellValue('A2', '序号');
        $sheet->setCellValue('B2', '档案号');
        $sheet->setCellValue('C2', '案卷题名');
        $sheet->setCellValue('D2', '案卷页数');
        $sheet->setCellValue('D3', '文字材料');
        $sheet->setCellValue('E3', '蓝图');
        $sheet->setCellValue('F3', '总页数');
        $sheet->setCellValue('G2', '保管期限');
        $sheet->setCellValue('H2', '起止日期');
        $sheet->setCellValue('I2', '形成单位');
        $sheet->setCellValue('J2', '卷内数量');
        /**
         * 顶部案卷目录样式设置
         */
        $sheet->getStyle('A1:J' . $this->totalRow)->getAlignment()->setVertical('center');//垂直居中
        $sheet->getStyle('A1:J' . $this->totalRow)->getAlignment()->setHorizontal('center');//水平居中
        $sheet->getStyle('B4:C' . $this->totalRow)->getAlignment()->setHorizontal('left');//左对齐
        $sheet->getStyle('A1:J' . $this->totalRow)->getAlignment()->setWrapText(true); //自动换行

        $sheet->getStyle('A1')->getFont()->setSize(20); //大小
        $sheet->getStyle('A1:J2')->getFont()->setBold(true); //粗体
        $sheet->getStyle('A2:J2')->getFont()->setSize(11); //大小
        $sheet->getStyle('D3:F3')->getFont()->setSize(11); //大小
        $sheet->getStyle('D3:F3')->getFont()->setBold(true); //粗体
        /**
         * 设置边框
         */
        $styleArray = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' =>  Border::BORDER_THIN //细边框
                ]
            ]
        ];
        $sheet->getStyle('A2:J'.$this->totalRow)->applyFromArray($styleArray);
    }

}
